﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Google.GData.Client;
using Google.Documents;
using System.Globalization;

namespace ResxLocalizationEditor.GoogleImport {
    public partial class DocumentsVisualizer : UserControl {
        public DocumentsVisualizer() {
            InitializeComponent();
        }

        delegate void GuiAction();

        public void LoadFolder(Document folder, string username, string password) {
            listDocuments.Items.Clear();
            listDocuments.Enabled = false;
            LoadButton.Enabled = false;

            ThreadPool.QueueUserWorkItem(new WaitCallback((o) => {
                try {
                    var settings = new RequestSettings(GoogleDocsImport.ApiAppKey, username, password);
                    settings.AutoPaging = true;

                    var request = new DocumentsRequest(settings);
                    var feed = request.GetFolderContent(folder);
                    var documents = feed.Entries.ToList(); //executes query

                    Invoke(new GuiAction(() => {
                        foreach (var doc in documents) {
                            var lvi = new ListViewItem(doc.Title);
                            lvi.Checked = true;
                            
                            var culture = GenerateCulture(doc);
                            if (culture == null) {
                                lvi.SubItems.Add("invalid");
                                lvi.BackColor = Color.Red;
                                lvi.Checked = false;
                                lvi.Tag = null;
                            }
                            else {
                                lvi.SubItems.Add((culture == CultureInfo.InvariantCulture) ? "Default" : culture.DisplayName);
                                lvi.Tag = new ImportableDocument {
                                    Document = doc,
                                    Language = culture
                                };
                            }
                            listDocuments.Items.Add(lvi);
                        }
                        
                        listDocuments.Enabled = true;
                    }));

                }
                catch (Exception ex) {
                    MessageBox.Show("Failed to retrieve contents of folder: " + ex.ToString());
                }
            }));
        }

        private CultureInfo GenerateCulture(Document doc) {
            if (doc == null)
                return null;

            string title = doc.Title;
            if (string.IsNullOrEmpty(title))
                return null;

            int firstSpace = title.IndexOf(' ');
            string firstWord = title.Substring(0, firstSpace);

            if ("default".Equals(firstWord, StringComparison.InvariantCultureIgnoreCase)) {
                //Default culture
                return CultureInfo.InvariantCulture;
            }

            try {
                var info = CultureInfo.GetCultureInfo(firstWord);
                return info;
            }
            catch (ArgumentException) {
                //Invalid culture, skip
                return null;
            }
        }

        public IEnumerable<ImportableDocument> SelectedDocuments {
            get {
                return (from item in listDocuments.CheckedItems.Cast<ListViewItem>()
                        let doc = item.Tag as ImportableDocument
                        where doc != null
                        select doc);
            }
        }

        private void Documents_itemCheck(object sender, ItemCheckEventArgs e) {
            var item = listDocuments.Items[e.Index];
            if (item.Tag == null) {
                //Keep invalid values unchecked
                e.NewValue = CheckState.Unchecked;
            }
        }

        private void Documents_itemChecked(object sender, ItemCheckedEventArgs e) {
            LoadButton.Enabled = (listDocuments.CheckedItems.Count > 0);
        }

    }
}
